from dbutils import db_exists, dbuser_exists, schema_exists, recreate_schema

def init_schema(schemaname, dbname, recreate):
    """Script to create schema for

    Assumptions:
    1. psql has been installed
    2. A database user called dbuser exists.
    2. A database called dbname exists and dbuser has sufficient privileges to create a schema on it.
    """
    import os, sys
    usr = os.popen('whoami').read().strip()

    # create schema
    from utils import create_engine_wrapper, get_conf, pg_url
    conf = get_conf()
    dbuser = conf["dbuser"]
    password = conf["password"]
    portnum = conf["portnum"]
    dbstring_usr = "%s://%s@:%s/postgres"%(pg_url(), usr, portnum)
    dbstring = "%s://%s:%s@localhost:%s/postgres"%(pg_url(), dbuser, password, portnum)
    dbstring_dbname = "%s://%s:%s@localhost:%s/%s"%(pg_url(), dbuser, password, portnum, dbname)
    db_usr = create_engine_wrapper(dbstring_usr)
    db = create_engine_wrapper(dbstring)
    db_dbname = create_engine_wrapper(dbstring_dbname)
    usr = os.popen('whoami').read().strip()
    if not dbuser_exists(db_usr, dbuser):
        sys.exit("dbuser '%s' does not exist\nrun the init_db.py script, exiting"%dbuser)
    if not db_exists(db, dbname):
        sys.exit("database '%s' does not exist\nrun the init_db.py script, exiting"%dbname)
    if not schema_exists(db_dbname, schemaname):
        conn = db_dbname.connect()
        conn.execute("commit")
        print "creating schema %s"%schemaname
        conn.execute("create schema %s"%schemaname)
    else:
        if recreate is True:
            recreate_schema(db_dbname, schemaname)
        elif recreate is False:
            sys.exit("schema %s exists - not recreating..."%schemaname)
        else:
            yn = raw_input("schema %s exists - delete and recreate? (Answer y or n) "%schemaname)
            if yn.lower().startswith('y'):
                recreate_schema(db_dbname, schemaname)
            else:
                sys.exit("schema %s exists - not recreating..."%schemaname)

if __name__ == '__main__':
    import sys, traceback
    from optparse import OptionParser
    usage = "usage: %prog [-r] schema database"
    parser = OptionParser(usage=usage)
    parser.add_option("-y", "--recreate", action="store_true", dest="recreate", help="delete schema and recreate")
    parser.add_option("-n", "--no-recreate", action="store_false", dest="recreate", help="do not recreate schema")
    (options, args) = parser.parse_args()
    if len(args) != 2:
        print "incorrect number of arguments"
        parser.print_help()
        sys.exit(1)

    schema = args[0]
    dbname = args[1]
    init_schema(schema, dbname, options.recreate)
